package com.example.gulimall.cart.interceptor;

import com.example.common.constant.AuthServerConstant;
import com.example.common.constant.CartServerConstant;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.cart.to.UserInfoTo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberResponseVo attribute = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_NAME);
        UserInfoTo userInfoTo=new UserInfoTo();
        if(attribute!=null){
            userInfoTo.setUserId(attribute.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equalsIgnoreCase(CartServerConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setTempUser(true);
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        if(userInfoTo.getUserKey()==null){
            String s = UUID.randomUUID().toString();
            userInfoTo.setUserKey(s);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getTempUser()){
            Cookie cookie = new Cookie(CartServerConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartServerConstant.TEMP_USER_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
